package com.frame.utils

import groovy.transform.CompileStatic
import groovy.transform.TypeChecked;

import java.io.*;

/**
 * 对象序列化工具
 * @author three
 * Created by three on 14-7-8.
 */
@CompileStatic
@TypeChecked
public class SerializeUtil {

    /**
     * 对象序列化
     * @param obj
     * @param <T>
     * @return
     * @throws java.io.IOException
     */
    public static <T> byte[] serialize(T obj) throws IOException, NullPointerException, NotSerializableException {
        if(obj==null){
            throw new NullPointerException("序列化对象为null");
        }
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;

        //序列化
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        byte[] bytes = baos.toByteArray();
        return bytes;

    }

    /**
     * 反序列化
     * @param bytes
     * @return
     * @throws java.io.IOException
     * @throws ClassNotFoundException
     */
    public static <T> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException, NullPointerException, ClassCastException {
        if(bytes==null){
            throw new NullPointerException("反序列化对象为null");
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (T)ois.readObject();

    }
}
